<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 市场动态模块
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2014-07-04 11:50:20 +0800 (五, 2014-07-04) $
 * @version : $Id: trend_model.php 114 2014-07-04 03:50:20Z spike $
 * @rev     : $Revision: 114 $
 */
class Trend_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    // --------------------------------------------------------------------
    
    /**
     * [编辑商品]
     * @param  [array]  $params [所有信息的数组]
     * @return [bool]
     */
    public function edit_trend($trend_id, Array $params)
    {

        if( FALSE === $this->get_trend($trend_id, TRUE) )
        {
            $this->set_error("编辑市场动态失败：无法找到市场动态[{$trend_id}]。");
            return FALSE;
        }

        $trend = array();

        $params = array(
            'title'     => $params['title']     ? xss_clean(trim($params['title']))     : NULL,
            'cover_img' => $params['cover_img'] ? xss_clean(trim($params['cover_img'])) : NULL,
            'desc'      => $params['desc']      ? xss_clean(trim($params['desc']))      : NULL,
        );

        /* 校验名开始 */
        if( isset($params['title']) )
        {
            if( ! validate_length($params['title'], 1, 50) )
            {
                $this->set_error("新增市场动态失败：标题最少1个字最多50个字。[{$params['title']}]。");
                return FALSE;
            }

            $this->load->dao('Trend_dao');
            $count = $this->Trend_dao->count(array(
                'status'      => TREND_STATUS_ON,
                'title'       => $params['title'],
                'trend_id <>' => $trend_id,
                'is_delete'   => UNDELETED,
            ));

            if( $count > 0)
            {
                $this->set_error("新增市场动态失败：标题已存在。[{$params['title']}]。");
                return FALSE;
            }
            $trend['title'] = $params['title'];
        }
        /* 校验名结束 */
      
        /* 校验描述开始 */
        if( isset($params['title']) )
        {
            $trend['desc'] = clean_html($params['desc']);
        }
        /* 校验描述结束 */

        /* 校验图片开始 */
         if( isset($params['cover_img']) )
        {
            $trend['cover_img'] = $params['cover_img'];
        }
        /* 校验图片结束 */

        if( ! $trend )
        {
            $this->set_error("编辑市场动态失败：没有需要编辑的内容。");
            return FALSE;
        }
        
        // 写入
        $trend['create_admin'] = login_info('admin_id');
        $trend['create_time']  = now_str();

        $this->load->dao('Trend_dao');
        if( ! $trend_id = $this->Trend_dao->update(
            $trend,
            array('trend_id'=>$trend_id)
        ) )
        {
            $this->set_error("编辑市场动态失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    /**
     * [新增商品]
     * @param  [array]  $params [所有信息的数组]
     * @return [bool]
     */
    public function add_trend(Array $params)
    {
        $params = array(
            'title'     => $params['title']     ? xss_clean(trim($params['title']))     : NULL,
            'cover_img' => $params['cover_img'] ? xss_clean(trim($params['cover_img'])) : NULL,
            'desc'      => $params['desc']      ? xss_clean(trim($params['desc']))      : NULL,
        );

        /* 校验名开始 */
        if( ! validate_length($params['title'], 1, 50) )
        {
            $this->set_error("新增市场动态失败：标题最少1个字最多50个字。[{$params['title']}]。");
            return FALSE;
        }

        $this->load->dao('Trend_dao');
        $count = $this->Trend_dao->count(array(
            'status'    => TREND_STATUS_ON,
            'title'     => $params['title'],
            'is_delete' => UNDELETED,
        ));

        if( $count > 0)
        {
            $this->set_error("新增市场动态失败：标题已存在。[{$params['title']}]。");
            return FALSE;
        }
        $trend['title'] = $params['title'];
        /* 校验名结束 */
      
        /* 校验描述开始 */
        if( $params['desc'] )
        {
            $trend['desc'] = clean_html($params['desc']);
        }
        /* 校验描述结束 */

        /* 校验图片开始 */
        if( ! $params['cover_img'] )
        {
            $this->set_error("新增市场动态失败：封面图片不能为空。[{$params['cover_img']}]。");
            return FALSE;
        }
        $trend['cover_img'] = $params['cover_img'];
        /* 校验图片结束 */
        
        // 写入
        $trend['status']       = TREND_STATUS_ON;
        $trend['is_delete']    = UNDELETED;
        $trend['create_admin'] = login_info('admin_id');
        $trend['create_time']  = now_str();

        $this->load->dao('Trend_dao');
        if( ! $trend_id = $this->Trend_dao->insert($trend))
        {
            $this->set_error("新增市场动态失败：无法写入数据库。");
            return FALSE;
        }

        return $trend_id;
    }

    // --------------------------------------------------------------------

    /**
     * [获得一个市场动态]
     * @param  [string]     $trend_id
     * @param  [bool]       $enable        [是否排除"关闭状态"]
     * @return [array/false]
     */
    public function get_trend($trend_id, $enable = TRUE)
    {
        if( ! validate($trend_id, 'TREND_ID') )
        {
            $this->set_error("获取市场动态失败：ID格式不正确。[{$trend_id}]");
            return FALSE;
        }
        
        $where = array(
            'trend_id'   => $trend_id,
            'is_delete'  => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = TREND_STATUS_ON;
        }

        $this->load->dao('Trend_dao');
        $trend = $this->Trend_dao->get_one($where);
        $trend['desc'] = htmlspecialchars_decode($trend['desc']);
        if( ! $trend)
        {
            $this->set_error("获取市场动态失败：无法找到市场动态。[{$trend_id}]");
            return FALSE;
        }

        return $trend;
    }

    // --------------------------------------------------------------------

    /**
     * [分页浏览]
     * @param  [array]  $params  [条件]
     * @param  [int]    $page    [当前页]
     * @param  [int]    $size    [页数，只允许app_config中"pagesize"的值]
     * @param  [string] $orderby [排序]
     * @return [array]
     */
    public function browse_trend($params, $page = NULL, $size = NULL, $orderby = '`trend_id` DESC')
    {
        $output = array(
            'size' => 0,
            'data' => array(),
            'total'=> 0,
        );

        $where = array(
            'is_delete' => UNDELETED,
        );

        if( ! empty($params['title']) )
        {
            $where['`title` LIKE'] = "%".xss_clean(trim($params['title']))."%";
        }

        if( ! empty($params['status']) )
        {
            $trend_status = $this->config->item('trend_status');
            if( $trend_status["{$params['status']}"] )
                $where['status'] = $params['status'];
        }
      
        if( ! empty($params['create_time_start']) && strtotime($params['create_time_start']) )
        {
            $where['`create_time` >'] = $params['create_time_start'];
        }

        if( ! empty($params['create_time_end']) && strtotime($params['create_time_end']) )
        {
            $where['`create_time` <'] = $params['create_time_end'];
        }

        if( ! empty($params['update_time_start']) && strtotime($params['update_time_start']) )
        {
            $where['`update_time` >'] = $params['update_time_start'];
        }

        if( ! empty($params['update_time_end']) && strtotime($params['update_time_end']) )
        {
            $where['`update_time` <'] = $params['update_time_end'];
        }
        
        $pagesize = $this->config->item('pagesize');
        $size     = isset($pagesize[$size]) ? $size : 10;
        $offset   = intval(($page-1)*$size) > 0 ? intval(($page-1)*$size) : 0;
        $total    = 0;

        $this->load->dao('Trend_dao');
        $data = $this->Trend_dao->get(
            $where, 
            '*', 
            $orderby, 
            $size, 
            $offset, 
            TRUE, 
            $total
        );

        $output['size']  = $size; 
        $output['data']  = $data; 
        $output['total'] = $total;

        return $output;
    }

    // --------------------------------------------------------------------
    
    /**
     * [改变评论状态]
     * 
     * @param  [string]  $goods_sn   [编码]
     * @param  [string]  $act        [操作类型]
     * @return [bool]
     */
    public function change_trend_status($trend_id, $act)
    {   
        if( ! $trend = $this->get_trend($trend_id, FALSE))
        {
            $this->set_error("修改市场动态状态失败：无法找到市场动态[{$trend_id}]。");
            return FALSE;
        }

        // 初始化数据
        $_status       = NULL;  //修改的状态
        $_allow_status = NULL;  //允许修改的状态
        $_update       = NULL;  //更新的数据
        
        switch (strtolower(trim($act)))
        {
            case 'on':
                    $_status       = TREND_STATUS_ON;
                    $_allow_status = array(TREND_STATUS_OFF);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            case 'off':
                    $_status       = TREND_STATUS_OFF;
                    $_allow_status = array(TREND_STATUS_ON);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            default:
                    $this->set_error("修改市场动态状态失败：未知的操作[{$act}]。");
                    return FALSE;
                break;
        }

        $status      = $this->config->item('trend_status');
        $status_name = (string)$status[$_status];

        // 验证状态
        $current_status = (int)$trend['status'];
        if($current_status === $_status)
        {
            $this->set_error("修改市场动态状态失败：无需修改。");
            return FALSE;
        }

        if( $_allow_status && ! in_array($current_status, $_allow_status))
        {
            $this->set_error("修改市场动态状态失败：不允许被修改为[{$status_name}]状态。");
            return FALSE;
        }

       
        // 只有符合条件才会被修改
        $this->load->dao('Trend_dao');
        $affected_row = $this->Trend_dao->update_in(
            $_update,
            array('status'   => $_allow_status),
            array('trend_id' => $trend_id)
            );
        if($affected_row<=0)
        {
            $this->set_error("修改市场动态状态失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    // --------------------------------------------------------------------
}
